<template>
  <div class="city-selector">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>城市选择</h3>
        </div>
      </template>
      <div class="city-list">
        <el-skeleton :rows="3" animated v-if="loading" />
        <template v-else>
          <el-radio-group v-model="selectedCity" @change="handleCityChange">
            <el-radio-button v-for="city in cities" :key="city" :label="city">{{ city }}</el-radio-button>
          </el-radio-group>
          <div class="district-selector" v-if="districts.length > 0">
            <h4>区域选择</h4>
            <el-checkbox-group v-model="selectedDistricts" @change="handleDistrictChange">
              <el-checkbox v-for="district in districts" :key="district" :label="district">{{ district }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </template>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'CitySelector',
  data() {
    return {
      loading: true,
      cities: [],
      districts: [],
      selectedCity: '',
      selectedDistricts: []
    };
  },
  created() {
    this.fetchCities();
  },
  methods: {
    async fetchCities() {
      try {
        this.loading = true;
        const response = await axios.get('/api/analysis/cities');
        this.cities = response.data;
        if (this.cities.length > 0) {
          this.selectedCity = this.cities[0];
          this.fetchDistricts(this.selectedCity);
        }
      } catch (error) {
        console.error('获取城市列表失败:', error);
        this.$message.error('获取城市列表失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    async fetchDistricts(city) {
      try {
        const response = await axios.get(`/api/analysis/districts?city=${city}`);
        this.districts = response.data;
        this.selectedDistricts = [];
      } catch (error) {
        console.error(`获取${city}的区域列表失败:`, error);
        this.$message.error(`获取${city}的区域列表失败，请稍后重试`);
      }
    },
    handleCityChange(city) {
      this.fetchDistricts(city);
      this.$emit('city-change', city);
    },
    handleDistrictChange(districts) {
      this.$emit('district-change', districts);
    }
  }
};
</script>

<style scoped>
.city-selector {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.city-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.el-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.district-selector {
  margin-top: 15px;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}
</style> 